package controller

import (
	"dta-apk/query/request"
	"dta-apk/query/response"
	"dta-apk/service"
	"dta-apk/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 版本列表
func versionList(ctx *gin.Context) *response.ResultRes {
	pageNum, err := strconv.Atoi(ctx.Query("pageNum"))
	if err != nil {
		return response.NewFailed(400, "参数错误")
	}
	pageSize, err := strconv.Atoi(ctx.Query("pageSize"))
	if err != nil {
		return response.NewFailed(400, "参数错误")
	}
	// 参数判断
	appId := ctx.Query("appId")
	if appId == "" {
		return response.NewParamFailed()
	}
	// 请求参数
	query := request.VersionPageQuery{
		AppId:    appId,
		Query:    ctx.Query("query"),
		PageNum:  pageNum,
		PageSize: pageSize,
	}
	// 查询版本列表
	data, ok := service.GetVersionList(&query)
	if ok {
		return response.NewSuccess(data)
	}

	return response.NewRequestFailed()

}

// 版本添加
func versionAdd(ctx *gin.Context) *response.ResultRes {
	var query request.VersionAddQuery
	ctx.ShouldBind(&query)
	// 保存版本信息
	msg, result := service.AddVersion(&query)
	if result {
		return response.NewSuccessMsg(nil, msg)
	}
	return response.NewMsgFailed(msg)
}

// 发布的版本列表
func PublishVersionList(ctx *gin.Context) *response.ResultRes {
	appId, isEx := ctx.GetQuery("appId")
	if !isEx {
		return response.NewParamFailed()
	}
	if appId == "" {
		return response.NewParamFailed()
	}
	result := service.GetPublishVersion(appId)
	return response.NewSuccess(result)
}

// 版本详细信息
func GetVersionById(ctx *gin.Context) *response.ResultRes {
	versionId, isEx := ctx.GetQuery("versionId")
	if !isEx {
		return response.NewParamFailed()
	}
	result := service.GetVersionInfo(versionId)
	return response.NewSuccess(result)
}

// apk文件下载
func DownloadApk(ctx *gin.Context) {
	versionId, isEx := ctx.GetQuery("versionId")
	if isEx {
		fileName, filePath := service.DownloadApkOfVersion(versionId)
		if fileName != "" {
			// 设置响应头
			ctx.Header("Content-Description", "File Transfer")
			ctx.Header("Content-Disposition", "attachment; filename="+fileName)
			ctx.Header("Content-Type", "application/octet-stream")
			ctx.Header("Content-Transfer-Encoding", "binary")
			// 将文件内容写入响应主体
			ctx.FileAttachment(filePath, fileName)
			defer utils.DeleteFile(filePath)
		}
	}
}
